package com.hyc.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hyc.annotation.UserLoginToken;
import com.hyc.entity.User;
import com.hyc.service.TokenService;
import com.hyc.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RestController
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private TokenService tokenService;

    @PostMapping("/login")
    public JSONObject login(@RequestBody User user) {
        JSONObject jsonObject = new JSONObject();
        User userInDB = userService.findByName(user.getName());
        if (userInDB == null) {
            jsonObject.put("message", "登录失败,用户不存在");
            return jsonObject;
        }

        if (!userInDB.getPassword().equals(user.getPassword())) {
            jsonObject.put("message", "登录失败,密码错误");
            return jsonObject;
        } else {
            String token = tokenService.generateToken(userInDB);
            jsonObject.put("token", token);
            jsonObject.put("user", userInDB);
            return jsonObject;
        }
    }

    @UserLoginToken
    @GetMapping("/findUser")
    public User findUser(Long id) {
        User user = userService.findUserById(id);
        log.info("查询到用户" + JSON.toJSONString(user));
        return user;
    }
}
